/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.web.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.validator.Assert;
import io.renren.modules.web.dao.UserDao;
import io.renren.modules.web.entity.UserEntity;
import io.renren.modules.web.form.LoginForm;
import io.renren.modules.web.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Map;


@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserDao, UserEntity> implements UserService {

	@Override
	public UserEntity queryByMobile(String mobile) {
		return baseMapper.selectOne(new QueryWrapper<UserEntity>().eq("mobile", mobile));
	}

	@Override
	public long login(LoginForm form) {
		UserEntity user = queryByMobile(form.getMobile());
		Assert.isNull(user, "手机号或密码错误");

		//密码错误
		if(!user.getPassword().equals(DigestUtils.sha256Hex(form.getPassword()))){
			throw new RRException("手机号或密码错误");
		}

		return user.getUserId();
	}

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String username = (String) params.get("userName");
		String type =(String) params.get("type");

		QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
		//条件 ...
		wrapper.like(StringUtils.isNotBlank(username),"username",username);
		wrapper.eq(StringUtils.isNotBlank(type),"type",type);
		IPage<UserEntity> page = this.page(new Query<UserEntity>().getPage(params), wrapper);

		return new PageUtils(page);
	}

	@Override
	public void deleteByIds(Long[] ids) {
		baseMapper.deleteBatchIds(Arrays.asList(ids));
	}

	@Override
	public UserEntity getById(Long id) {
		QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
		wrapper.eq("user_id",id);

		UserEntity userEntity = this.baseMapper.selectOne(wrapper);
		return userEntity;
	}



}
